{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "W7rEsKyWcxmu"
      },
      "source": [
        "##### Copyright 2021 The TF-Agents Authors.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "nQnmcm0oI1Q-"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G6aOV15Wc4HP"
      },
      "source": [
        "# Checkpointer and PolicySaver\n",
        "\n",
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/agents/tutorials/10_checkpointer_policysaver_tutorial\"\u003e\n",
        "    \u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003e\n",
        "    View on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/10_checkpointer_policysaver_tutorial.ipynb\"\u003e\n",
        "    \u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003e\n",
        "    Run in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/agents/blob/master/docs/tutorials/10_checkpointer_policysaver_tutorial.ipynb\"\u003e\n",
        "    \u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003e\n",
        "    View source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/10_checkpointer_policysaver_tutorial.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M3HE5S3wsMEh"
      },
      "source": [
        "## Introduction\n",
        "\n",
        "`tf_agents.utils.common.Checkpointer` is a utility to save/load the training state, policy state, and replay_buffer state to/from a local storage.\n",
        "\n",
        "`tf_agents.policies.policy_saver.PolicySaver` is a tool to save/load only the policy, and is lighter than `Checkpointer`. You can use `PolicySaver` to deploy the model as well without any knowledge of the code that created the policy.\n",
        "\n",
        "In this tutorial, we will use DQN to train a model, then use `Checkpointer` and `PolicySaver` to show how we can store and load the states and model in an interactive way. Note that we will use TF2.0's new saved_model tooling and format for `PolicySaver`.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vbTrDrX4dkP_"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Opk_cVDYdgct"
      },
      "source": [
        " If you haven't installed the following dependencies, run:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Jv668dKvZmka"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "!sudo apt-get update\n",
        "!sudo apt-get install -y xvfb ffmpeg python-opengl\n",
        "!pip install pyglet\n",
        "!pip install 'imageio==2.4.0'\n",
        "!pip install 'xvfbwrapper==0.2.9'\n",
        "!pip install tf-agents"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bQMULMo1dCEn"
      },
      "outputs": [],
      "source": [
        "from __future__ import absolute_import\n",
        "from __future__ import division\n",
        "from __future__ import print_function\n",
        "\n",
        "import base64\n",
        "import imageio\n",
        "import io\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "import os\n",
        "import shutil\n",
        "import tempfile\n",
        "import tensorflow as tf\n",
        "import zipfile\n",
        "import IPython\n",
        "\n",
        "try:\n",
        "  from google.colab import files\n",
        "except ImportError:\n",
        "  files = None\n",
        "from tf_agents.agents.dqn import dqn_agent\n",
        "from tf_agents.drivers import dynamic_step_driver\n",
        "from tf_agents.environments import suite_gym\n",
        "from tf_agents.environments import tf_py_environment\n",
        "from tf_agents.eval import metric_utils\n",
        "from tf_agents.metrics import tf_metrics\n",
        "from tf_agents.networks import q_network\n",
        "from tf_agents.policies import policy_saver\n",
        "from tf_agents.policies import py_tf_eager_policy\n",
        "from tf_agents.policies import random_tf_policy\n",
        "from tf_agents.replay_buffers import tf_uniform_replay_buffer\n",
        "from tf_agents.trajectories import trajectory\n",
        "from tf_agents.utils import common\n",
        "\n",
        "tempdir = os.getenv(\"TEST_TMPDIR\", tempfile.gettempdir())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AwIqiLdDCX9Q"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "# Set up a virtual display for rendering OpenAI gym environments.\n",
        "import xvfbwrapper\n",
        "xvfbwrapper.Xvfb(1400, 900, 24).start()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AOv_kofIvWnW"
      },
      "source": [
        "## DQN agent\n",
        "We are going to set up DQN agent, just like in the previous colab. The details are hidden by default as they are not core part of this colab, but you can click on 'SHOW CODE' to see the details."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cStmaxredFSW"
      },
      "source": [
        "### Hyperparameters"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "both",
        "id": "yxFs6QU0dGI_"
      },
      "outputs": [],
      "source": [
        "env_name = \"CartPole-v1\"\n",
        "\n",
        "collect_steps_per_iteration = 100\n",
        "replay_buffer_capacity = 100000\n",
        "\n",
        "fc_layer_params = (100,)\n",
        "\n",
        "batch_size = 64\n",
        "learning_rate = 1e-3\n",
        "log_interval = 5\n",
        "\n",
        "num_eval_episodes = 10\n",
        "eval_interval = 1000"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w4GR7RDndIOR"
      },
      "source": [
        "### Environment"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fZwK4d-bdI7Z"
      },
      "outputs": [],
      "source": [
        "train_py_env = suite_gym.load(env_name)\n",
        "eval_py_env = suite_gym.load(env_name)\n",
        "\n",
        "train_env = tf_py_environment.TFPyEnvironment(train_py_env)\n",
        "eval_env = tf_py_environment.TFPyEnvironment(eval_py_env)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0AvYRwfkeMvo"
      },
      "source": [
        "### Agent"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cUrFl83ieOvV"
      },
      "outputs": [],
      "source": [
        "#@title\n",
        "q_net = q_network.QNetwork(\n",
        "    train_env.observation_spec(),\n",
        "    train_env.action_spec(),\n",
        "    fc_layer_params=fc_layer_params)\n",
        "\n",
        "optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)\n",
        "\n",
        "global_step = tf.compat.v1.train.get_or_create_global_step()\n",
        "\n",
        "agent = dqn_agent.DqnAgent(\n",
        "    train_env.time_step_spec(),\n",
        "    train_env.action_spec(),\n",
        "    q_network=q_net,\n",
        "    optimizer=optimizer,\n",
        "    td_errors_loss_fn=common.element_wise_squared_loss,\n",
        "    train_step_counter=global_step)\n",
        "agent.initialize()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "p8ganoJhdsbn"
      },
      "source": [
        "### Data Collection"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XiT1p78HdtSe"
      },
      "outputs": [],
      "source": [
        "#@title\n",
        "replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n",
        "    data_spec=agent.collect_data_spec,\n",
        "    batch_size=train_env.batch_size,\n",
        "    max_length=replay_buffer_capacity)\n",
        "\n",
        "collect_driver = dynamic_step_driver.DynamicStepDriver(\n",
        "    train_env,\n",
        "    agent.collect_policy,\n",
        "    observers=[replay_buffer.add_batch],\n",
        "    num_steps=collect_steps_per_iteration)\n",
        "\n",
        "# Initial data collection\n",
        "collect_driver.run()\n",
        "\n",
        "# Dataset generates trajectories with shape [BxTx...] where\n",
        "# T = n_step_update + 1.\n",
        "dataset = replay_buffer.as_dataset(\n",
        "    num_parallel_calls=3, sample_batch_size=batch_size,\n",
        "    num_steps=2).prefetch(3)\n",
        "\n",
        "iterator = iter(dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8V8bojrKdupW"
      },
      "source": [
        "### Train the agent"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-rDC3leXdvm_"
      },
      "outputs": [],
      "source": [
        "#@title\n",
        "# (Optional) Optimize by wrapping some of the code in a graph using TF function.\n",
        "agent.train = common.function(agent.train)\n",
        "\n",
        "def train_one_iteration():\n",
        "\n",
        "  # Collect a few steps using collect_policy and save to the replay buffer.\n",
        "  collect_driver.run()\n",
        "\n",
        "  # Sample a batch of data from the buffer and update the agent's network.\n",
        "  experience, unused_info = next(iterator)\n",
        "  train_loss = agent.train(experience)\n",
        "\n",
        "  iteration = agent.train_step_counter.numpy()\n",
        "  print ('iteration: {0} loss: {1}'.format(iteration, train_loss.loss))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vgqVaPnUeDAn"
      },
      "source": [
        "### Video Generation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZY6w-fcieFDW"
      },
      "outputs": [],
      "source": [
        "#@title\n",
        "def embed_gif(gif_buffer):\n",
        "  \"\"\"Embeds a gif file in the notebook.\"\"\"\n",
        "  tag = '\u003cimg src=\"data:image/gif;base64,{0}\"/\u003e'.format(base64.b64encode(gif_buffer).decode())\n",
        "  return IPython.display.HTML(tag)\n",
        "\n",
        "def run_episodes_and_create_video(policy, eval_tf_env, eval_py_env):\n",
        "  num_episodes = 3\n",
        "  frames = []\n",
        "  for _ in range(num_episodes):\n",
        "    time_step = eval_tf_env.reset()\n",
        "    frames.append(eval_py_env.render())\n",
        "    while not time_step.is_last():\n",
        "      action_step = policy.action(time_step)\n",
        "      time_step = eval_tf_env.step(action_step.action)\n",
        "      frames.append(eval_py_env.render())\n",
        "  gif_file = io.BytesIO()\n",
        "  imageio.mimsave(gif_file, frames, format='gif', fps=60)\n",
        "  IPython.display.display(embed_gif(gif_file.getvalue()))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y-oA8VYJdFdj"
      },
      "source": [
        "### Generate a video\n",
        "Check the performance of the policy by generating a video."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FpmPLXWbdG70"
      },
      "outputs": [],
      "source": [
        "print ('global_step:')\n",
        "print (global_step)\n",
        "run_episodes_and_create_video(agent.policy, eval_env, eval_py_env)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7RPLExsxwnOm"
      },
      "source": [
        "## Setup Checkpointer and PolicySaver\n",
        "\n",
        "Now we are ready to use Checkpointer and PolicySaver."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g-iyQJacfQqO"
      },
      "source": [
        "### Checkpointer\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2DzCJZ-6YYbX"
      },
      "outputs": [],
      "source": [
        "checkpoint_dir = os.path.join(tempdir, 'checkpoint')\n",
        "train_checkpointer = common.Checkpointer(\n",
        "    ckpt_dir=checkpoint_dir,\n",
        "    max_to_keep=1,\n",
        "    agent=agent,\n",
        "    policy=agent.policy,\n",
        "    replay_buffer=replay_buffer,\n",
        "    global_step=global_step\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MKpWNZM4WE8d"
      },
      "source": [
        "### Policy Saver"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8mDZ_YMUWEY9"
      },
      "outputs": [],
      "source": [
        "policy_dir = os.path.join(tempdir, 'policy')\n",
        "tf_policy_saver = policy_saver.PolicySaver(agent.policy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1OnANb1Idx8-"
      },
      "source": [
        "### Train one iteration"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ql_D1iq8dl0X"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "print('Training one iteration....')\n",
        "train_one_iteration()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eSChNSQPlySb"
      },
      "source": [
        "### Save to checkpoint"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "usDm_Wpsl0bu"
      },
      "outputs": [],
      "source": [
        "train_checkpointer.save(global_step)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gTQUrKgihuic"
      },
      "source": [
        "### Restore checkpoint\n",
        "\n",
        "For this to work, the whole set of objects should be recreated the same way as when the checkpoint was created."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "l6l3EB-Yhwmz"
      },
      "outputs": [],
      "source": [
        "train_checkpointer.initialize_or_restore()\n",
        "global_step = tf.compat.v1.train.get_global_step()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Nb8_MSE2XjRp"
      },
      "source": [
        "Also save policy and export to a location"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3xHz09WCWjwA"
      },
      "outputs": [],
      "source": [
        "tf_policy_saver.save(policy_dir)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Mz-xScbuh4Vo"
      },
      "source": [
        "The policy can be loaded without having any knowledge of what agent or network was used to create it. This makes deployment of the policy much easier.\n",
        "\n",
        "Load the saved policy and check how it performs"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "J6T5KLTMh9ZB"
      },
      "outputs": [],
      "source": [
        "saved_policy = tf.saved_model.load(policy_dir)\n",
        "run_episodes_and_create_video(saved_policy, eval_env, eval_py_env)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MpE0KKfqjc0c"
      },
      "source": [
        "## Export and import\n",
        "The rest of the colab will help you export / import checkpointer and policy directories such that you can continue training at a later point and deploy the model without having to train again.\n",
        "\n",
        "Now you can go back to 'Train one iteration' and train a few more times such that you can understand the difference later on. Once you start to see slightly better results, continue below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fd5Cj7DVjfH4"
      },
      "outputs": [],
      "source": [
        "#@title Create zip file and upload zip file (double-click to see the code)\n",
        "def create_zip_file(dirname, base_filename):\n",
        "  return shutil.make_archive(base_filename, 'zip', dirname)\n",
        "\n",
        "def upload_and_unzip_file_to(dirname):\n",
        "  if files is None:\n",
        "    return\n",
        "  uploaded = files.upload()\n",
        "  for fn in uploaded.keys():\n",
        "    print('User uploaded file \"{name}\" with length {length} bytes'.format(\n",
        "        name=fn, length=len(uploaded[fn])))\n",
        "    shutil.rmtree(dirname)\n",
        "    zip_files = zipfile.ZipFile(io.BytesIO(uploaded[fn]), 'r')\n",
        "    zip_files.extractall(dirname)\n",
        "    zip_files.close()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hgyy29doHCmL"
      },
      "source": [
        "Create a zipped file from the checkpoint directory."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nhR8NeWzF4fe"
      },
      "outputs": [],
      "source": [
        "train_checkpointer.save(global_step)\n",
        "checkpoint_zip_filename = create_zip_file(checkpoint_dir, os.path.join(tempdir, 'exported_cp'))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VGEpntTocd2u"
      },
      "source": [
        "Download the zip file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "upFxb5k8b4MC"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "if files is not None:\n",
        "  files.download(checkpoint_zip_filename) # try again if this fails: https://github.com/googlecolab/colabtools/issues/469"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VRaZMrn5jLmE"
      },
      "source": [
        "After training for some time (10-15 times), download the checkpoint zip file,\n",
        "and go to \"Runtime \u003e Restart and run all\" to reset the training,\n",
        "and come back to this cell. Now you can upload the downloaded zip file,\n",
        "and continue the training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kg-bKgMsF-H_"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "upload_and_unzip_file_to(checkpoint_dir)\n",
        "train_checkpointer.initialize_or_restore()\n",
        "global_step = tf.compat.v1.train.get_global_step()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uXrNax5Zk3vF"
      },
      "source": [
        "Once you have uploaded checkpoint directory, go back to 'Train one iteration' to continue training or go back to 'Generate a video' to check the performance of the loaded poliicy."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OAkvVZ-NeN2j"
      },
      "source": [
        "Alternatively, you can save the policy (model) and restore it.\n",
        "Unlike checkpointer, you cannot continue with the training, but you can still deploy the model. Note that the downloaded file is much smaller than that of the checkpointer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s7qMn6D8eiIA"
      },
      "outputs": [],
      "source": [
        "tf_policy_saver.save(policy_dir)\n",
        "policy_zip_filename = create_zip_file(policy_dir, os.path.join(tempdir, 'exported_policy'))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rrGvCEXwerJj"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "if files is not None:\n",
        "  files.download(policy_zip_filename) # try again if this fails: https://github.com/googlecolab/colabtools/issues/469"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DyC_O_gsgSi5"
      },
      "source": [
        "Upload the downloaded policy directory (exported_policy.zip) and check how the saved policy performs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bgWLimRlXy5z"
      },
      "outputs": [],
      "source": [
        "#@test {\"skip\": true}\n",
        "upload_and_unzip_file_to(policy_dir)\n",
        "saved_policy = tf.saved_model.load(policy_dir)\n",
        "run_episodes_and_create_video(saved_policy, eval_env, eval_py_env)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HSehXThTm4af"
      },
      "source": [
        "## SavedModelPyTFEagerPolicy\n",
        "\n",
        "If you don't want to use TF policy, then you can also use the saved_model directly with the Python env through the use of `py_tf_eager_policy.SavedModelPyTFEagerPolicy`.\n",
        "\n",
        "Note that this only works when eager mode is enabled."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iUC5XuLf1jF7"
      },
      "outputs": [],
      "source": [
        "eager_py_policy = py_tf_eager_policy.SavedModelPyTFEagerPolicy(\n",
        "    policy_dir, eval_py_env.time_step_spec(), eval_py_env.action_spec())\n",
        "\n",
        "# Note that we're passing eval_py_env not eval_env.\n",
        "run_episodes_and_create_video(eager_py_policy, eval_py_env, eval_py_env)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7fvWqfJg00ww"
      },
      "source": [
        "## Convert policy to TFLite\n",
        "\n",
        "See [TensorFlow Lite Inference](https://tensorflow.org/lite/guide/inference) for more details."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "z9zonVBJ0z46"
      },
      "outputs": [],
      "source": [
        "converter = tf.lite.TFLiteConverter.from_saved_model(policy_dir, signature_keys=[\"action\"])\n",
        "converter.target_spec.supported_ops = [\n",
        "  tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n",
        "  tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n",
        "]\n",
        "tflite_policy = converter.convert()\n",
        "with open(os.path.join(tempdir, 'policy.tflite'), 'wb') as f:\n",
        "  f.write(tflite_policy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rsi3V9QdxJUu"
      },
      "source": [
        "### Run inference on TFLite model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4GeUSWyZxMlN"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "interpreter = tf.lite.Interpreter(os.path.join(tempdir, 'policy.tflite'))\n",
        "\n",
        "policy_runner = interpreter.get_signature_runner()\n",
        "print(policy_runner._inputs)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eVVrdTbRxnOC"
      },
      "outputs": [],
      "source": [
        "policy_runner(**{\n",
        "    '0/discount':tf.constant(0.0),\n",
        "    '0/observation':tf.zeros([1,4]),\n",
        "    '0/reward':tf.constant(0.0),\n",
        "    '0/step_type':tf.constant(0)})"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "TF-Agent Checkpointer / PolicySaver Colab",
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "12InF1JXmpmA_qCgRScMO736YjqRoHWxT",
          "timestamp": 1627303299731
        },
        {
          "file_id": "https://github.com/tensorflow/agents/blob/master/docs/tutorials/10_checkpointer_policysaver_tutorial.ipynb",
          "timestamp": 1627302328422
        }
      ],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
